<?php


namespace app\shop\controller\pc;

use app\Request;
use app\shop\model\user\UserModel;
use app\shop\model\order\OrderModel;
use app\shop\model\user\DepartmentModel;
use app\shop\model\user\AdminRoleModel;
use app\shop\service\user\UserService;
use app\shop\validate\UserValidate;
use app\shop\service\until\FileService;
use app\shop\common\consts\Consts;
use Carbon\Carbon;

use app\BaseController;
use think\Validate;

class DepartmentController extends BaseController
{
    /**
     * 新增或修改员工信息
     */
    public function modifyEmployees()
    {
        try {
            $data = $this->request->only(['user_id', 'mobile', 'realname', 'department_id']);

            // 假设通过中间件获取用户身份信息
            $userInfo = $this->request->middleware('userInfo');
            $role_id = $userInfo->role_id;

            // 如果 user_id 存在，则是修改已有用户信息
            if (!empty($data['user_id'])) {
                // 查询用户是否存在
                $user = UserModel::find($data['user_id']);
                if (!$user) {
                    throw new \Exception('用户不存在');
                }
            } else {
                Validate(UserValidate::class)->scene('apisaleAdd')->check($data);
                // 如果 user_id 不存在，则是新增用户信息
                $user = new UserModel();

                // 设置默认密码和用户编号
                $salt = random(4);
                $password = password_hash('123456' . $salt, PASSWORD_DEFAULT);
                $user_sn = random(6, 'letter');
                $avatar = "/image/127/2024-07-29/66a7099c48494.png";
                $user->avatar = $avatar;
                $user->password = $password;
                $user->salt = $salt;
                $user->user_sn = $user_sn;
                // 根据用户身份设置角色ID
                if ($role_id == Consts::SERVICE_LEADER_ID) {
                    $user->role_id = Consts::DESIGN_LEADER_ID;
                } elseif ($role_id == Consts::SALE_LEADER_ID) {
                    $user->role_id = Consts::SALE_ID;
                } elseif ($role_id == Consts::DESIGN_LEADER_ID) {
                    $user->role_id = Consts::DESIGN_ID;
                } else {
                    return $this->success("该用户无法添加");
                }
            }
            // 查询手机号是否被占用（排除当前用户）
            if (isset($data['mobile']) && $data['mobile'] !== '') {
                $existingUser = UserModel::where('mobile', $data['mobile'])
                    ->where('user_id', '<>', $data['user_id'])
                    ->find();
                if ($existingUser) {
                    throw new \Exception('手机号已被占用');
                }
            }
            // 更新或新增用户信息
            if (isset($data['mobile'])) {
                $user->mobile = $data['mobile'];
            }
            if (isset($data['realname'])) {
                $user->realname = $data['realname'];
            }
            if (isset($data['department_id'])) {
                $user->department_id = $data['department_id'];
            }
            // 保存修改或新增
            $user->save();

            if (!empty($data['user_id'])) {
                return $this->success("修改成功");
            } else {
                return $this->success("新增成功");
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 新增设计师
     */
    public function designerAdd()
    {
        try {
            //用户身份
            $userInfo = $this->request->middleware('userInfo');
            $role_id = $userInfo->role_id;
            $data = $this->request->only(['mobile', 'realname', 'department_id']);
            Validate(UserValidate::class)->scene('apisaleAdd')->check($data);
            //查询手机号
            $usermobile = UserModel::where('mobile', $data['mobile'])->find();
            if ($usermobile) {
                throw new \Exception('手机号已被占用');
            }
            // 根据不同的用户身份设置不同的 role_id
            switch ($role_id) {
                case Consts::SERVICE_LEADER_ID:
                    $data['role_id'] = Consts::DESIGN_LEADER_ID;
                    break;
                case Consts::DESIGN_LEADER_ID:
                    $data['role_id'] = Consts::DESIGN_ID;
                    break;
                default:
                    // 默认情况下，可能需要处理或者抛出异常
                    throw new \Exception('你没有权限！');
            }
            $data['salt'] = random(4);
            $data['password'] = password_hash(123456 . $data['salt'], PASSWORD_DEFAULT);
            $data['user_sn'] = random(6, 'letter');
            $data['role_id'] = 8;
            $user = new UserModel();
            $user->save($data);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 新增销售
     */
    public function saleAdd()
    {
        try {
            $data = $this->request->only(['mobile', 'realname', 'department_id']);
            Validate(UserValidate::class)->scene('apisaleAdd')->check($data);
            //查询手机号
            $userInfo = UserModel::where('mobile', $data['mobile'])->find();
            if ($userInfo) {
                throw new \Exception('手机号已被占用');
            }
            $data['salt'] = random(4);
            $data['password'] = password_hash(123456 . $data['salt'], PASSWORD_DEFAULT);
            $data['user_sn'] = random(6, 'letter');
            $data['role_id'] = 6;
            $user = new UserModel();
            $user->save($data);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 删除用户 设计师和销售都一样
     */
    public function designerDel()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $userRoleId = $userInfo->role_id;
            if ($userRoleId != Consts::SALE_LEADER_ID && $userRoleId != Consts::SERVICE_LEADER_ID && $userRoleId != Consts::DESIGN_LEADER_ID) {
                throw new \Exception('你没有权限！');
            }
            $userId = $this->request->param('user_id', '', 'trim');
            // 查找要删除的用户数据，如果找不到会抛出异常
            $user = UserModel::where('user_id', $userId)->find();
            // 执行删除操作
            $deleted = $user->delete();
            if ($deleted) {
                return $this->success('删除成功');
            } else {
                throw new \Exception('删除失败');
            }
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 查询设计师部门
     */
    public function designerDepartment()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $role_id = $userInfo->role_id;
            $department_id = $userInfo->department_id;
            if (
                $role_id == Consts::DESIGN_LEADER_ID
            ) {
                $department = DepartmentModel::where('id', $department_id)->select();
            } else if ($role_id == Consts::SERVICE_LEADER_ID) {
                $department = DepartmentModel::where('pid', 16)->select();
            }
            return $this->success($department);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 查询销售部门
     */
    public function saleDepartment()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $departmentId = $userInfo['department_id'];
            $department = DepartmentModel::where('pid', $departmentId)->select();
            return $this->success($department);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 售后总监添加登录码
     */
    public function addLoginCode()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $userRoleId = $userInfo->role_id;
            if ($userRoleId != Consts::SERVICE_LEADER_ID && $userRoleId != Consts::DESIGN_LEADER_ID) {
                throw new \Exception('你没有权限！');
            }
            $data = $this->request->only(['user_id', 'morning_start_work_time', 'afternoon_end_work_time']);

            Validate(UserValidate::class)->scene('addLoginCode')->check($data);

            $startTime = strtotime(date('Y-m-d ' . $data['morning_start_work_time']));
            $endTime = strtotime(date('Y-m-d ' . $data['afternoon_end_work_time']));
            UserService::generateCode($data['user_id'], $startTime, $endTime);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 售后总监修改登录码
     */
    public function modifyLoginCode()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $userRoleId = $userInfo->role_id;
            if ($userRoleId != Consts::SERVICE_LEADER_ID && $userRoleId != Consts::DESIGN_LEADER_ID) {
                throw new \Exception('你没有权限！');
            }
            // 获取所有可能的字段
            $data = $this->request->only(['user_id', 'morning_start_work_time', 'afternoon_end_work_time', 'login_code']);
            Validate(UserValidate::class)->scene('addLoginCode')->check($data);

            $startTime = strtotime(date('Y-m-d ' . $data['morning_start_work_time']));
            $endTime = strtotime(date('Y-m-d ' . $data['afternoon_end_work_time']));

            UserService::generateCode($data['user_id'], $startTime, $endTime, $data['login_code']);
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 生成登录码，并传递到前端
     */
    public function generate()
    {
        try {

            $loginCode = rand(100000, 999999);
            return $this->success($loginCode); // 返回生成的登录码
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 售后总监 查看设计师经理登陆码
     */
    public function queryLoginCode()
    {
        try {
            $users = UserModel::where('role_id', Consts::DESIGN_LEADER_ID)->field('user_id,role_id,department_id, realname,login_code,morning_start_work_time,morning_end_work_time,afternoon_start_work_time,afternoon_end_work_time')->select();
            foreach ($users as &$v) {
                $v['department_name'] = DepartmentModel::where('id', $v['department_id'])->value('name'); //部门名称
                $v['role_id'] = AdminRoleModel::where('id', $v['role_id'])->value('role_name'); //身份 
                // 格式化时间戳为时分秒格式，如果为空则不转换
                if (!empty($v['morning_start_work_time'])) {
                    $v['morning_start_work_time'] = date('H:i', $v['morning_start_work_time']);
                }
                if (!empty($v['morning_end_work_time'])) {
                    $v['morning_end_work_time'] = date('H:i', $v['morning_end_work_time']);
                }
                if (!empty($v['afternoon_start_work_time'])) {
                    $v['afternoon_start_work_time'] = date('H:i', $v['afternoon_start_work_time']);
                }
                if (!empty($v['afternoon_end_work_time'])) {
                    $v['afternoon_end_work_time'] = date('H:i', $v['afternoon_end_work_time']);
                }
            }
            return $this->success($users);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 登陆码管理 查看设计师登陆码
     */
    public function designerLoginCode()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            $users = UserModel::where('role_id', Consts::DESIGN_ID)
                ->where('department_id', $userInfo["department_id"])
                ->field('user_id,role_id,department_id, realname,login_code,morning_start_work_time,morning_end_work_time,afternoon_start_work_time,afternoon_end_work_time')
                ->select();
            foreach ($users as &$v) {
                $v['department_id'] = DepartmentModel::where('id', $v['department_id'])->value('name'); //部门名称
                $v['role_id'] = AdminRoleModel::where('id', $v['role_id'])->value('role_name'); //身份
                // 格式化时间戳为时分秒格式，如果为空则不转换
                if (!empty($v['morning_start_work_time'])) {
                    $v['morning_start_work_time'] = date('H:i', $v['morning_start_work_time']);
                }
                if (!empty($v['morning_end_work_time'])) {
                    $v['morning_end_work_time'] = date('H:i', $v['morning_end_work_time']);
                }
                if (!empty($v['afternoon_start_work_time'])) {
                    $v['afternoon_start_work_time'] = date('H:i', $v['afternoon_start_work_time']);
                }
                if (!empty($v['afternoon_end_work_time'])) {
                    $v['afternoon_end_work_time'] = date('H:i', $v['afternoon_end_work_time']);
                }
            }
            return $this->success($users);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    //根据用户id查询用户信息
    public function getUserInfo()
    {
        try {
            // 假设这里是你从数据库查询用户信息的逻辑
            $userId = $this->request->param("user_id");
            $user = UserModel::where('user_id', $userId)->find();
            return $this->success($user);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}
